package com.linran.javaweb.advice;

import com.linran.javaweb.annotation.PageVO;
import com.linran.javaweb.util.Converter;
import com.linran.javaweb.util.PageUtil;
import com.linran.javaweb.vo.PageVo;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Optional;

@RestControllerAdvice
public class GlobalPageParamAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        //默认拦截所有拦截器
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //该注解注解的方法只返回总数量，在此拦截进行分页参数封装
        if (Optional.ofNullable(methodParameter.getMethodAnnotation(PageVO.class)).isPresent() && o instanceof Long) {
            return PageUtil.getPageVO(Converter.getAsLong(o));
        }
        //其他返回参数原样返回
        return o;
    }
}
